class Rand {
    constructor(prng = Math.random) {
        this.prng = prng
    }

    position(dim) {
        const x = Math.floor(this.prng() * dim.width)
        const y = Math.floor(this.prng() * dim.height)
        return {x, y} // NOTE: object property shorthand, same as writing { x: x, y: y}
    }

    choice(arr) {
        return arr[Math.floor(this.prng() * arr.length)]
    }
}

class RandStyle extends Rand {
    constructor(playerPos, gemPos, prng = Math.random) {
        super(prng);
        this.playerPos = playerPos
        this.gemPos = gemPos
        this.cellStyle = ['cell']
        this.terrains = ['desert', 'forest', 'mountain', 'swamp']
    }

    #call(newPos) {
        if (this.playerPos.x === newPos.x && this.playerPos.y === newPos.y)
            return 'player'

        if (this.gemPos.x === newPos.x && this.gemPos.y === newPos.y)
            return 'diamond'

        // if (!tile.isVisited)
        //     return [tile.terrain, 'cloaked']
        return this.choice(this.terrains)
    }

    call(newPos) {
        return this.cellStyle.concat([this.#call(newPos)])
    }
}

class GameMap {
    constructor(mapSize) {
        this.mapSize = mapSize
        this.mapWidth = mapSize.width
        this.mapHeight = mapSize.height

        this.playerPos = {
            x: Math.floor(this.mapWidth / 2),
            y: Math.floor(this.mapHeight / 2)
        }

        this.gemPos = new Rand().position(this.mapSize)

        this.randStyle = new RandStyle(this.playerPos, this.gemPos)
    }

    newCell(x, y) {
        let cell = document.createElement('div')
        const styleClasses = this.randStyle.call({x: x, y: y})
        styleClasses.forEach(e => cell.classList.add(e))
        return cell
    }

    build(container) {
        container.replaceChildren()

        for (let x = 0; x < this.mapHeight; x++)
            for (let y = 0; y < this.mapWidth; y++)
                container.appendChild(this.newCell(x, y))
    }
}

const mapSize = {width: 5, height: 5}
// const mapSize = {width: 15, height: 15}

// let container = document.getElementById('chessboard')
let container = document.querySelector('#chessboard')
let gameMap = new GameMap(mapSize)

gameMap.build(container)

